<template>
  <div class="batch-tool">
    <DilalogList :availableOrderNum="availableOrderNum" :contact="contact" :serviceImeisNum="getOrderNum"
      :fileName="this.service?.serviceName" @exportOrderList="exportOrderList" @analisyImei="analisyImei"
      ref="dialogList"></DilalogList>
    <div class="batch-tool-main">
      <el-container style="height: 100%;">
        <el-aside class="left" v-if="!mobile">
          <div class="user-info">
            <div class="avator" slot="reference">
              <img :src="getUserInfo.headimgurl" alt="" />
            </div>
            <div class="info">
              <div class="name">{{ getUserInfo.nickname ?? getUserInfo.userName }}</div>
              <div class="money">
                {{ $t('余额') }}：
                <span>{{ getUserInfo.pointsBalance }}</span>
              </div>
              <div class="topup" @click="$router.push('/charge')">{{ $t('充值') }}</div>
            </div>
          </div>
          <div>
            <div class="btn">
              <el-button :type="!fuwu ? 'primary' : 'default'" @click="fuwu = false">常用服务</el-button>
              <el-button :type="fuwu ? 'primary' : 'default'" @click="fuwu = true">服务列表</el-button>
            </div>
            <div>
              <div v-if="fuwu" v-show="fuwu">
                <div style="padding: 10px 5px 10px;">
                  <el-input :placeholder="$t('搜索服务')" v-model="searchText" prefix-icon="el-icon-search"
                    @input="handleSearch"></el-input>
                </div>
                <el-menu :default-openeds="activeNames" class="el-menu-vertical-demo" @open="handleOpen"
                  @close="handleClose" background-color="#F7F9FE" text-color="#333" :collapse="isCollapse"
                  active-text-color="#ffd04b">
                  <el-submenu :index="key" v-for="(services, key) in serviceMap" :key="key">
                    <template slot="title">
                      <!-- <i class="el-icon-s-order"></i> -->
                      <span>{{ $t(key) }}</span>
                    </template>
                    <el-menu-item @click="choseService(service)" :title="$t(service.serviceName)" class="e-m-i"
                      v-for="(service, index) in services" :index="key + '_' + index" :key="index">
                      <div class="p-button" style="width: 300px;line-height: 1.5;padding-right: 30px;">
                        <div class="l">
                          <div class="t1">{{ service.serviceId }}</div>
                          <div class="t2">{{ $t(service.serviceName) }}</div>
                        </div>
                        <div class="r">
                          <div class="b b1">￥{{ service.price }}</div>
                          <div class="b b2">{{ service.time }}</div>
                        </div>
                      </div>
                    </el-menu-item>
                  </el-submenu>
                </el-menu>



              </div>
              <div v-else>
                <div v-for="(services, key) in serviceMap" :key="key">
                  <div v-show="$store.state.star.includes(service.serviceId)" @click="choseService(service)"
                    class="p-button" v-for="(service, index) in services" :key="index">
                    <div class="l">
                      <div class="t1">{{ service.serviceId }}</div>
                      <div class="t2">{{ $t(service.serviceName) }}</div>
                    </div>
                    <div class="r">
                      <div class="b b1">￥{{ service.price }}</div>
                      <div class="b b2">{{ service.time }}</div>
                    </div>
                  </div>
                </div>
                <div v-if="!($store.state.star && $store.state.star.length)"
                  style="color: #999;font-size: .12rem;text-align: center;padding-top: .2rem;">暂无</div>
              </div>
            </div>
          </div>

        </el-aside>

        <el-container>
          <HeaderWx v-if="mobile" />
          <el-header class="header">
            <BatchQueryToolHeader :serviceId="service?.serviceId" @refreshOrderImei="refreshOrderImei"
              @showImportImei="showImportImei" @showExport="showExport" @commitImeis="commitImeis"
              @cancleCommit="cancleCommit" @clearImeis="clearImeis" @resetFailedImei="resetFailedImei" :pause="pause">
            </BatchQueryToolHeader>
          </el-header>
          <el-main :class="[mobile ? 'cont-mobile' : 'cont']">
            <div style="text-align: center;">
              <b :class="[mobile ? 'mobile-t' : '']"
                style="word-break: break-word;white-space: normal;text-align: center;">#{{
                  service?.serviceId }}
                {{ $t(service?.serviceName) }}{{ $t('价格') }}：￥{{ service?.price }} {{ $t('预计时间') }}：{{ service?.time
                }}<br>
                {{ $t('总数') }}：{{ serviceImeis.length }} {{ $t('上传中') }}：{{ process }} {{ $t('成功')
                }}：{{
                  success }} {{ $t('失败') }}：{{ error }}</b>
            </div>
            <el-table :class="[mobile ? 'table-m' : '']" border @sort-change="handleSortChange" :data="sortedTableData"
              row-key="item">
              <el-table-column prop="test" type="index" label="序号" width="50" align="center"></el-table-column>

              <template v-for="(item, index) in schemas">
                <el-table-column class-name="allowDrag" :filters="item.filters" :filter-method="serviceImeisFilter"
                  :key="`schemas_${index}`" :prop="schemas[index].prop" :label="item.label" :width="item.width"
                  :sortable="item.sortable">
                  align="center">
                  <template slot-scope="scope">
                    <template v-if="item.isHtml">
                      <div :style="{ color: scope.row[item.prop]?.color }" v-html="scope.row[item.prop]?.desc"></div>
                    </template>
                    <div v-else>
                      {{ $t(scope.row[item.prop]) }}
                    </div>
                  </template>
                </el-table-column>
              </template>

            </el-table>
          </el-main>
        </el-container>
      </el-container>
    </div>
    <div class="all-service" v-if="mobile" @click="showAllService = true">
      <span>服</span>
      <span>务</span>
      <span>列</span>
      <span>表</span>
    </div>
    <el-drawer custom-class="drawer" title="服务列表" :visible.sync="showAllService" direction="ltr" size="80%"
      style="max-width: 320px;" :show-close="false">
      <template #title>
        <div class="btn">
          <el-button :type="!fuwu ? 'primary' : 'default'" @click="fuwu = false">常用服务</el-button>
          <el-button :type="fuwu ? 'primary' : 'default'" @click="fuwu = true">服务列表</el-button>
        </div>
      </template>
      <div class="zd">
        <div v-if="fuwu">
          <div style="padding: 0 10px 10px;">
            <el-input :placeholder="$t('搜索服务')" v-model="searchText" size="small" prefix-icon="el-icon-search"
              @input="handleSearch"></el-input>
          </div>
          <el-collapse v-model="activeNames">
            <el-collapse-item :name="key" v-for="(services, key) in serviceMap" :key="key">
              <template slot="title">
                <b class="services-title">{{ $t(key) }}</b>
              </template>
              <div @click="choseService(service)" class="p-button" v-for="(service, index) in services" :key="index">
                <div class="l">
                  <div class="t1">{{ service.serviceId }}</div>
                  <div class="t2">{{ $t(service.serviceName) }}</div>
                </div>
                <div class="r">
                  <div class="b b1">￥{{ service.price }}</div>
                  <div class="b b2">{{ service.time }}</div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>


        <div v-else>
          <div v-for="(services, key) in serviceMap" :key="key">
            <div v-show="$store.state.star.includes(service.serviceId)" @click="choseService(service)" class="p-button"
              v-for="(service, index) in services" :key="index">
              <div class="l">
                <div class="t1">{{ service.serviceId }}</div>
                <div class="t2">{{ $t(service.serviceName) }}</div>
              </div>
              <div class="r">
                <div class="b b1">￥{{ service.price }}</div>
                <div class="b b2">{{ service.time }}</div>
              </div>
            </div>
          </div>
          <div v-if="!($store.state.star && $store.state.star.length)"
            style="color: #999;font-size: .12rem;text-align: center;padding-top: .2rem;">暂无</div>
        </div>

      </div>
      <div class="hide-menu" @click="showAllService = false">
        <span>隐</span>
        <span>藏</span>
        <span>菜</span>
        <span>单</span>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import apiService from "@/api/apiService";
import { getUser, replace, getSchemas, fetchAllData, extractModelFromResult } from "@/utils";
// import storage from "store";
// import appConfig from "@/config/appConfig";
import * as util from '@/utils/index'
import DilalogList from './DilalogList'
import BatchQueryToolHeader from './BatchQueryToolHeader'
import Sortable from "sortablejs";
import { mapGetters } from "vuex";
import { isMobile } from "@/utils";
import HeaderWx from "@/components/home/HeaderWx.vue";

export default {
  name: "BatchQueryTool",
  components: {
    DilalogList, BatchQueryToolHeader, HeaderWx
  },
  data() {
    return {
      //暂停提交按钮
      pause: false,
      serviceImeiMap: new Map(),
      serviceImeis: [],
      serviceMap: null,
      service: null,
      user: null,
      isCollapse: false,
      contact: null,
      sortable: null,
      schemas: null,
      loopRefreshInterval: null,
      availableOrderNum: 0,
      sortKey: '',//当前点击排序的列
      sortOrder: '',//排序
      showAllService: false,
      fuwu: true,
      searchText: '',
      activeNames: [],
    }
  },
  created() {
    //初始化页面缩放
    // this.handleViewPort()
    //加载用户信息
    this.loadUser()
    //加载联系客服信息
    this.loadContact()
    // 获取收藏列表
    this.$store.dispatch('getStar')
  },
  mounted() {
    const { serviceId } = this.$route.query
    window.scale = 1
    this.$nextTick(() => {
      //获取所有服务信息
      apiService.get("/all-service", {}).then(res => {
        this.serviceList = res.data
        this.serviceMap = this.groupedByParent(this.serviceList)
        if (this.serviceList.length > 0) {
          if (serviceId) {
            this.service = this.serviceList.filter(service => service.serviceId === serviceId)[0]
          } else {
            this.service = this.serviceList[0]
          }
          this.choseService(this.service)
        }
      })

      //初始化展示项
      this.schemasInit()
      //表格拖拽方法
      this.columnDrop();

      //先简单做，没过5秒轮询获取订单状态
      this.loopRefresh()

    })
  },
  beforeDestroy() {
    if (this.loopRefreshInterval) {
      clearInterval(this.loopRefreshInterval);
    }
  },
  computed: {
    ...mapGetters(["getUserInfo"]),
    getOrderNum: function () {
      return this.serviceImeis.length
    },
    success() {
      const { serviceImeis } = this;
      const num = serviceImeis.map(u => {
        return u.state === '完成'
      }).filter(u => u === true)
      return num.length
    },
    error() {
      const { serviceImeis } = this;
      const num = serviceImeis.map(u => {
        return u.state === '失败'
      }).filter(u => u === true)
      return num.length
    },
    process() {
      const { serviceImeis } = this;
      const num = serviceImeis.map(u => {
        return u.state === '正在处理'
      }).filter(u => u === true)
      return num.length
    },
    sortedTableData() {
      const { serviceImeis, sortKey, sortOrder } = this;
      if (!sortKey) {
        return serviceImeis;
      }

      return serviceImeis.slice().sort((a, b) => {
        let a_desc = a[sortKey]?.desc
        let b_desc = b[sortKey]?.desc
        if (!a_desc) {
          a_desc = a[sortKey]
        }
        if (!b_desc) {
          b_desc = b[sortKey]
        }

        // console.log(sortOrder)
        if (sortOrder === 'ascending') {
          // console.log('升序')
          if (typeof a_desc === 'object') {
            if (typeof a_desc === 'string') {
              return a_desc.localeCompare(b_desc);
            } else if (typeof a_desc === 'number') {
              return a_desc - b_desc;
            }
          } if (typeof a_desc === 'string') {
            // console.log(a_desc+'  '+b_desc)
            return a_desc.localeCompare(b_desc);
          } else if (typeof a_desc === 'number') {
            return a_desc - b_desc;
          }
          return a_desc - b_desc
        } else if (sortOrder === 'descending') {
          // console.log('降序')
          if (typeof b_desc === 'object') {
            if (typeof b_desc === 'string') {
              return b_desc.localeCompare(a_desc);
            } else if (typeof b_desc === 'number') {
              return b_desc - a_desc;
            }
          } if (typeof b_desc === 'string') {
            return a_desc.localeCompare(b_desc);
          } else if (typeof b_desc === 'number') {
            return b_desc - a_desc;
          }
          return b_desc - a_desc
        }
        return 0;
      });
    },
    mobile() {
      return isMobile();
    },
  },
  watch: {
    schemas: {
      handler() {
        this.$refs.dialogList.schemas = this.schemas
      }
    },
    serviceImeis: {
      handler() {
        //监听serviceImeis，如果imei列表更新了，就更新筛选项
        this.schemasFilter()
      }
    },
    service: {
      handler() {
        const pointsBalance = getUser().pointsBalance
        const servicePrice = this.service?.price
        this.availableOrderNum = Math.floor(pointsBalance / servicePrice)

        this.$refs.dialogList.exportObj.fileName = this.service?.serviceName
      }
    }
  },
  methods: {
    // eslint-disable-next-line no-unused-vars
    handleSortChange({ column, prop, order }) {
      this.sortKey = prop
      this.sortOrder = order;
    },
    loopRefresh() {
      this.loopRefreshInterval = setInterval(() => {
        this.refreshOrderImei()
      }, 3000)
    },
    /**
     * 列拖拽
     */
    columnDrop() {
      var _this = this;
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
      this.sortable = Sortable.create(wrapperTr, {
        draggable: ".allowDrag",//允许拖拽元素(el-table-column上设置class-name为允许拖拽)
        animation: 180,
        delay: 0,
        //之前调用onEnd方法会出现表格DOM不更新以及表头对不上的情况所以更换为onUpdate方法
        //参考资料 https://www.jianshu.com/p/fd6eb408d8bd
        onUpdate: function (evt) {
          //修改items数据顺序
          var newIndex = evt.newIndex;
          var oldIndex = evt.oldIndex;
          const newItem = wrapperTr.children[newIndex];
          const oldItem = wrapperTr.children[oldIndex];

          // 先删除移动的节点
          wrapperTr.removeChild(newItem)
          // 再插入移动的节点到原有节点，还原了移动的操作
          if (newIndex > oldIndex) {
            wrapperTr.insertBefore(newItem, oldItem)
          } else {
            wrapperTr.insertBefore(newItem, oldItem.nextSibling)
          }
          // 更新items数组(index-1是第一列有一个多选列不支持拖拽,否则会有排序错乱的问题)
          var item = _this.schemas.splice(oldIndex - 1, 1);
          _this.schemas.splice(newIndex - 1, 0, item[0]);
          // 下一个tick就会走patch更新

        }

      })
    },
    /**
     * 触发表格重绘
     */
    reDrawTable(evt) {
      this.$nextTick(() => {
        const oldItem = this.schemas[evt.oldIndex];
        this.schemas.splice(evt.oldIndex, 1);
        this.schemas.splice(evt.newIndex, 0, oldItem);
      });
    },
    /**
     * 返回到首页
     */
    backToHome() {
      this.replace('/')
    },
    /**
     * 加载用户信息
     */
    loadUser() {
      this.$store.dispatch('getCurrentUserInfo')
      // getCurrentUser().then(() => {
      //   this.user = getUser()
      //   if (!this.user) {
      //     storage.remove(appConfig.APP_USER)
      //     storage.remove(appConfig.ACCESS_TOKEN_NAME)
      //     location.reload()
      //   }
      // })
    },
    /**
     * 加载联系客服信息
     */
    loadContact() {
      apiService.get("/contact-info", {}).then(res => {
        this.contact = res.data
      })
    },
    /**
     * 解析导入imei组件传的数据
     * @param serviceImeis
     */
    analisyImei(serviceImeis) {
      if (!this.service) {
        this.$message.warning('请先选择服务')
        return
      }
      if (serviceImeis.length === 0) {
        return;
      }
      let imeis = []
      for (let i = 0; i < serviceImeis.length; i++) {
        // if (!this.serviceImeis.map(x => x.imei).includes(serviceImeis[i].imei)) {
        imeis.push(JSON.parse(JSON.stringify(serviceImeis[i])))
        // }
      }

      let imeisInMap = this.serviceImeiMap.get(this.service?.serviceId);
      if (imeisInMap === undefined) {
        imeisInMap = []
      }
      //将新解析的imei插入到顶部
      imeisInMap.unshift(...imeis)
      this.serviceImeis = JSON.parse(JSON.stringify(imeisInMap))
      this.serviceImeiMap.set(this.service?.serviceId, imeisInMap)
      //解析好数据之后更新缓存
      localStorage.setItem('order-imei', JSON.stringify(Array.from(this.serviceImeiMap)))
    },
    updateServiceImeiMap(orderImeis) {
      const serviceList = this.serviceImeiMap.get(this.service?.serviceId);
      for (let i = 0; i < serviceList.length; i++) {
        const service = serviceList[i];
        const filterServiceImeis = orderImeis.filter(x => x.imei === service.imei);
        if (filterServiceImeis.length > 0) {
          serviceList[i] = JSON.parse(JSON.stringify(filterServiceImeis[0]));
        }
      }
    },
    //导出Imei信息
    showExport() {
      console.log(this.serviceImeis)
      const ids = this.serviceImeis.filter(x => x.id !== undefined).map(x => x.id)
      console.log(`output->ids`, ids)
      if (ids.length === 0) {
        this.$message.error("没有可以导出的imei")
        return
      }

      this.$refs.dialogList.exportDialogVisible = true;
    },
    exportOrderList(exportObj) {
      const ids = this.serviceImeis.filter(x => x.id !== undefined).map(x => x.id)
      const param = {
        orderBy: "desc",
        orderFiled: "update_time",
        orderIds: ids
      }
      fetchAllData("/order-list", param).then(result => {
        this.exportList(result, exportObj)
      }).catch(error => {
        console.log(error)
        this.$message.error('导出订单失败')
      })
    },
    /**
     * 导出imei信息
     */
    exportList(arr, exportObj) {
      const orderIdList = arr.map(x => x.id)
      const fileName = exportObj.fileName
      const selectFieldNameList = exportObj.checkList

      const downloadExcelRq = {
        orderIdList: orderIdList,
        fileName: fileName,
        selectFieldNameList: selectFieldNameList
      }
      // apiService.post("/downloadExcell", downloadExcelRq,{
      //     responseType: 'blob'
      // }).then(response => {
      //     const url = window.URL.createObjectURL(new Blob([response]));
      //     const link = document.createElement('a');
      //     link.href = url;
      //     link.setAttribute('download', fileName+'.xlsx'); // 设置下载文件的名字
      //     document.body.appendChild(link);
      //     link.click();
      //     URL.revokeObjectURL(url);
      // }).catch(error => {
      //     console.error('Error downloading the excel file:', error);
      // });
      apiService.post("/downloadExcellToServer", downloadExcelRq).then(response => {
        if (response.code === 0) {
          const url = 'https://www.unlocktop1.com/userapi/downloadExcellFormServer/' + response.data + "/" + fileName
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName + '.xlsx');
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(url);
        }

      }).catch(error => {
        console.error('Error downloading the excel file:', error);
      });

    },
    //清空imei数据
    clearImeis() {
      this.serviceImeiMap = new Map()
      this.serviceImeis = []
      //清空之后更新缓存
      localStorage.removeItem('order-imei')
    },
    cancleCommit() {
      console.log('暂停成功')
      this.$message.success('暂停成功')
      this.pause = false;
    },
    resetFailedImei() {
      for (let i = 0; i < this.serviceImeis.length; i++) {
        if (this.serviceImeis[i].state === '失败' || this.serviceImeis[i].state === '余额不足') {
          this.$set(this.serviceImeis, i, {
            imei: this.serviceImeis[i].imei,
            remark: "",
            state: "已导入"
          });
        }
      }
      this.updateServiceImeiMap(this.serviceImeis)
      localStorage.setItem('order-imei', JSON.stringify(Array.from(this.serviceImeiMap)))
    },
    //提交imei数据
    async commitImeis() {
      if (!this.service?.serviceId) {
        this.$message.error("请选择服务")
        return
      }

      this.pause = true;

      //筛选出未提交的订单
      let unCommitOrderImeis = this.serviceImeis.filter(x => x.state === '已导入')

      //按照15个拆分，分批次提交

      const unCommitOrderImeisLenth = unCommitOrderImeis.length;
      const esn = 15;

      for (let currnetIndex = 0; currnetIndex < unCommitOrderImeisLenth && this.pause;) {
        let currentUnCommitOrderImeis = [];
        let imeis = [];
        if (currnetIndex + esn > unCommitOrderImeisLenth) {
          currentUnCommitOrderImeis = unCommitOrderImeis.slice(currnetIndex, unCommitOrderImeisLenth)
        } else {
          currentUnCommitOrderImeis = unCommitOrderImeis.slice(currnetIndex, currnetIndex + esn)
        }
        imeis = currentUnCommitOrderImeis.map(x => x.imei).join('\n')
        currnetIndex = currnetIndex + esn;
        await this.commitBatch(currentUnCommitOrderImeis, imeis)
      }

      this.pause = false;
    },
    async commitBatch(currentUnCommitOrderImeis, imeis) {
      if (!imeis) {
        this.$message.error("请输入订单内容")
        return
      }
      const params = {
        serviceId: this.service.serviceId,
        serviceNumber: imeis,
        retail: false
      }
      await apiService.post("/submit-order", params).then(res => {
        if (res.code === 0) {
          if (res.data.failReason) {
            this.$message.error(res.data.failReason)
          } else {
            // this.$message.success("订单提交成功")
            currentUnCommitOrderImeis.forEach(x => {
              x.serviceId = this.service.serviceId
              x.serviceName = this.service.serviceName
              x.price = this.service.price
            })

            //更新订单信息（id信息）
            this.updateOrderInfoAfterCommit(res.data, currentUnCommitOrderImeis)

            this.updateServiceImeiMap(currentUnCommitOrderImeis)
            localStorage.setItem('order-imei', JSON.stringify(Array.from(this.serviceImeiMap)))
            this.loadUser()
          }
        } else {
          // this.$message.error(errorMsg(res))
        }
        // eslint-disable-next-line no-unused-vars
      }).catch(error => {
        // this.$message.error(error)
      })
    },
    //更新订单信息，在提交imei之后
    updateOrderInfoAfterCommit(data, unCommitOrderImeis) {
      const orderList = data?.orders;
      const existedIMEI = data?.existedIMEI;
      const validateFailIMEI = data?.validateFailIMEI;
      const pointFailIMEI = data?.pointFailIMEI;
      const map = new Map(orderList.map(order => [order.imei, order]));
      unCommitOrderImeis.forEach(x => {
        const orderImei = map.get(x.imei)
        if (orderImei) {
          x.state = '已提交';
          x.id = orderImei.id
          x.createTime = orderImei.create_time
        } else if (validateFailIMEI.includes(x.imei)) {
          x.state = '提交失败，请检查IMEI/SN的真实性';
        } else if (existedIMEI.includes(x.imei)) {
          x.state = '订单已存在，请勿重复提交';
        } else if (pointFailIMEI.includes(x.imei)) {
          x.state = '余额不足';
        } else {
          x.state = '提交失败，请检查IMEI/SN的真实性';
        }
      })
    },
    // 刷新订单信息
    refreshOrderImei() {
      //先刷新用户余额信息
      this.loadUser()
      //筛选出有id的订单
      let commitOrderImeiIds = this.serviceImeis.filter(x => x.id).map(x => x.id)
      if (commitOrderImeiIds.length === 0) {
        return
      }
      //通过订单id拿到订单信息
      fetchAllData("/order-list", {
        "orderIds": commitOrderImeiIds
      }).then(dataList => {
        if (dataList && dataList.length > 0) {
          const map = new Map(dataList.map(order => [order.id, order]));
          this.serviceImeis.filter(x => x.id).forEach(x => {
            const orderImei = map.get(x.id)
            if (orderImei) {
              x.state = util.stateMapping(orderImei.ap_result)
              x.result = orderImei.result
              //将拆分成列的数据展示到页面上（此处是新增列）
              try {
                const keys = Object.keys(orderImei.result_map)
                keys.forEach(key => {
                  this.updateShame(key)
                  //这里是将列的值赋值
                  try {
                    const valJson = JSON.parse(orderImei.result_map[key])
                    x[key] = valJson
                  } catch (e) {
                    x[key] = {
                      desc: orderImei.result_map[key]
                    }
                  }

                  //将分列出来的动态key保存
                  if (!x.dynamic) {
                    x.dynamic = []
                  }
                  if (!x.dynamic.includes(key)) {
                    x.dynamic.push(key)
                  }
                })
                // eslint-disable-next-line no-empty
              } catch (e) {
                console.log('处理失败:' + JSON.parse(orderImei.result_map | ''))
              }

              try {
                x.json_result = JSON.parse(JSON.stringify(orderImei.json_result))
                // eslint-disable-next-line no-empty
              } catch (e) {
                console.log('处理失败:' + orderImei.json_result)
              }

              x.model = extractModelFromResult(orderImei.result)

            }
          })
          this.updateServiceImeiMap(this.serviceImeis)
          localStorage.setItem('order-imei', JSON.stringify(Array.from(this.serviceImeiMap)))
        }
      })
    },
    //点击服务触发事件，进入服务

    choseService(service) {
      if (window.innerWidth <= 991) {
        this.isCollapse = true
      }
      this.schemas?.splice(0, this.schemas?.length)
      this.schemas = getSchemas()
      this.service = service
      let imeisArray = localStorage.getItem('order-imei')
      let imeisMap = new Map(JSON.parse(imeisArray));
      this.serviceImeiMap = imeisMap
      let imeisInMap = imeisMap.get(this.service?.serviceId);
      if (imeisInMap !== undefined) {
        this.serviceImeis = JSON.parse(JSON.stringify(imeisInMap))
        this.serviceImeis.forEach(serviceImei => {
          //将动态key加入
          if (serviceImei?.dynamic) {
            serviceImei.dynamic.forEach(key => {
              this.updateShame(key)
            })
          }
        })
      } else {
        this.serviceImeis = []
      }

      if (this.mobile) {
        this.showAllService = false
      }
    },
    //根据serviceImei的key更新列
    updateShame(key) {
      if (!this.schemas?.map(schema => schema.label).includes(key)) {
        this.schemas?.push({
          disabled: true,
          isCheck: true,
          fixed: true,
          label: key,
          prop: key,
          isHtml: true,
          sortable: true
        })
      }
    },
    //表格筛选
    serviceImeisFilter(value, row, column) {
      const property = column['property'];
      if (row[property]?.desc) {
        return row[property]?.desc === value;
      }
      return row[property] === value;
    },
    schemasInit() {
      this.schemas = getSchemas()
    },
    //更新表格筛选项
    schemasFilter() {
      this.schemas.forEach(schema => {
        if (schema) {
          schema.filters = []
          this.serviceImeis.forEach(serviceImei => {
            let val = serviceImei[schema.prop]?.desc
            if (!val) {
              val = serviceImei[schema.prop]
            }
            if (!schema.filters.map(x => x.value)
              .includes(val)) {
              schema.filters.push({
                text: val,
                value: val,
              })
            }

          })
        }
      })
    },
    // eslint-disable-next-line no-unused-vars
    handleOpen(key, keyPath) {
    },
    // eslint-disable-next-line no-unused-vars
    handleClose(key, keyPath) {
    },

    //展示导入imei组件
    showImportImei() {
      this.$refs.dialogList.isImportImei = true;
    },
    //关闭导入imei组件
    closeImportImei() {
      this.isImportImei = false;
    },
    replace,
    //展示联系人联系方式
    closeContact() {
      this.isShowContact = false;
    },
    //关闭联系人联系方式
    showContact() {
      this.$refs.dialogList.isShowContact = true;
    },
    //将imei服务按照父亲id分组
    groupedByParent(list) {
      return list.reduce((acc, item) => {
        const key = item.parent;
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(item);
        return acc;
      }, {})
    },
    handleSearch() {
      let filterList = this.serviceList.filter(x => this.likeCompare(x, this.searchText))
      this.serviceMap = this.groupedByParent(filterList)
      /* 搜索时全展开 */
      if (this.searchText) {
        this.activeNames = Object.keys(this.serviceMap)
      } else {
        this.activeNames = []
      }
    },
    likeCompare(x, queryString) {
      // console.log((String)(x.value).indexOf(queryString))
      return (String)(x.serviceName).indexOf(queryString) !== -1
        || (String)(x.parent).indexOf(queryString) !== -1
        || (String)(x.serviceId).indexOf(queryString) !== -1
    },
  },
};
</script>


<style lang="scss" scoped>
.drawer {
  background-color: transparent;
}

.all-service {
  position: fixed;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  background-color: #4D9EFC;
  font-size: 14px;
  color: #fff;
  padding: 2px 6px;
}

.batch-tool-main {
  height: 100vh;

  .left {
    height: 100%;
    position: relative;
    overflow: auto;
    background-color: #F7F9FE;
    min-width: 100px;

    .user-info {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-left: 20px;
      padding-top: 20px;
      position: sticky;
      top: 0;
      left: 0;
      z-index: 2;
      background-color: #F7F9FE;
      padding-bottom: 20px;

      .avator {
        width: 60px;
        height: 60px;
        border-radius: 6px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .info {
        color: #333;
        font-size: 14px;
        padding-left: 10px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .topup {
          background-image: linear-gradient(to right, #F6EDD9, #E6D2A0);
          color: #bf8d5e;
          padding: 2px 10px;
          margin-top: 5px;
          font-size: 12px;
          cursor: pointer;

        }
      }
    }

    .el-menu-vertical-demo {}
  }
}

.el-aside {
  height: 100%;
  color: #333;
  background-color: #F7F9FE;
}

.header {
  height: unset !important;
  flex-shrink: 0;
}

.btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  button {
    flex: 1;
    margin: 0 5px;
  }
}

.p-button {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: .05rem;
  margin: .05rem .05rem 0;
  border: 1px solid #f2f2f2;
  border-radius: 6px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .06);
  background-color: #d7e9ff;

  .l {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    font-size: .14rem;
    margin-top: -0.05rem;

    .t1 {
      color: #5288e8;
    }

    .t2 {
      color: #666666;
      font-size: .13rem;
      font-weight: bold;
    }
  }

  .r {
    display: flex;
    align-items: center;
    padding-top: .1rem;

    .b {
      border-radius: 6px;
      font-size: .12rem;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      width: .5rem;
      height: .2rem;
      font-weight: bold;


      &.b1 {
        background-color: #fe5858;
      }

      &.b2 {
        background-color: #51c28f;
        margin-left: 5px;
      }
    }
  }
}

.hide-menu {
  position: absolute;
  left: 100%;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  background-color: #4D9EFC;
  font-size: 14px;
  color: #fff;
  padding: 2px 6px;
}

.zd {
  border-radius: 10px;
  overflow: hidden;
  position: relative;
  position: relative;





  .services-title {
    width: 100%;
    text-align: center;
    line-height: 1.5;
  }





  .p-button-c {
    text-align: center;
    box-sizing: border-box;
    display: unset;
    flex-wrap: wrap;
    margin: auto;
    width: 100%;
  }
}

.e-m-i {
  max-width: 300px;
  white-space: nowrap;
  /* 确保文本在一行内显示 */
  overflow: hidden;
  /* 超出部分隐藏 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
  cursor: pointer;
  /* 鼠标样式 */
}

.e-m-i:hover {
  overflow: visible;
  /* 鼠标悬停时显示全文 */
  white-space: normal;
  /* 允许换行 */
}

.mobile-t {
  font-size: .12rem;
}

.cont-mobile {
  padding: 0 10px 10px;
}

.table-m {
  margin-top: 10px;
}

::v-deep .el-header {
  padding: 0;
}

::v-deep .table-m .el-table__cell {
  padding: 2px 0;
}

::v-deep .el-drawer__header {
  padding: 10px 10px 0;
  margin-bottom: 10px;
}

::v-deep .el-drawer {
  overflow: visible;
}

::v-deep .cell {
  font-size: .12rem;
}

::v-deep .el-menu-item {
  padding-left: 0 !important;
  padding-right: 0;
  background-color: transparent !important;
  overflow: hidden;
  white-space: wrap;
}

::v-deep .e-m-i:hover {
  overflow: hidden;
  white-space: wrap;
}

::v-deep .el-menu-item,
.el-submenu__title {
  height: auto;
}

::v-deep .el-submenu .el-menu-item {
  height: auto;
}
</style>